<template>
    <div class="app-container">
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain size="mini" @click="handleAdd">新增</el-button>
            </el-col>
        </el-row>
        <el-form :model="queryParams" size="small" :inline="true">
            <el-form-item label="标题" prop="title">
                <el-input v-model="queryParams.title" placeholder="请输入标题" clearable
                    @keyup.enter.native="handleQuery"></el-input>
            </el-form-item>
            <el-form-item label="选择栏目" prop="columnId">
                <el-select v-model="queryParams.columnId" placeholder="请选择栏目" clearable>
                    <el-option v-for="column in columnList" :key="column.columnId" :label="column.columnName"
                        :value="column.columnId" />
                </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="岗位状态" clearable>
                    <el-option v-for="dict in dict.type.wa_publish_article" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="mini" @click="handleQuery">查询</el-button>
                <el-button type="primary" size="mini" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>


        <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
            <el-table-column label="序号" align="center" type="index" />
            <el-table-column label="标题" align="center" prop="title" />
            <el-table-column label="栏目" align="center" prop="columnId">
                <template slot-scope="scope">
                    {{ scope.row.columnName || '未知栏目' }}
                </template>
            </el-table-column>
            <el-table-column label="创建人" align="center" prop="createBy" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="150px">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.wa_publish_article" :value="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding" width="300px">
                <template slot-scope="scope">
                    <!-- 草稿状态下（status=0)显示发布，编辑，删除，预览 -->
                    <template v-if="scope.row.status == statusEnum.DRAFT">
                        <el-button type="info" @click="handlePublish(scope.row)" size="small" plain>发布</el-button>
                        <el-button type="info" @click="handleUpdate(scope.row)" size="small" plain>编辑</el-button>
                        <el-button type="info" @click="handleDelete(scope.row)" size="small" plain>删除</el-button>
                        <el-button type="info" @click="handlePreview(scope.row)" size="small" plain>预览</el-button>
                    </template>
                    <!-- 已发布状态显示撤回，预览 -->
                    <template v-else-if="Number(scope.row.status) == statusEnum.PUBLISHED">
                        <el-button type="info" @click="handleRecall(scope.row)" size="small" plain>撤回</el-button>
                        <el-button type="info" @click="handlePreview(scope.row)" size="small" plain>预览</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />



        <!-- 添加或修改岗位对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body :close-on-click-modal="false"
            @close="handleDialogClose">

            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="选择栏目" prop="columnId">
                    <el-select v-model="form.columnId" placeholder="请选择栏目" clearable>
                        <el-option v-for="column in columnList" :key="column.columnId" :label="column.columnName"
                            :value="column.columnId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="文章名称" prop="articleName">
                    <el-input v-model="form.articleName" placeholder="请输入文章名称" />
                </el-form-item>
                <el-form-item label="文章标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入文章标题" />
                </el-form-item>
                <el-form-item label="副标题" prop="subTitle">
                    <el-input v-model="form.subTitle" placeholder="请输入文章副标题" />
                </el-form-item>

                <el-form-item label="封面图片">
                    <el-upload class="avatar-uploader" action="/dev-api/publish/article/upload"
                        :before-upload="beforeUpload" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                        :file-list="fileList" :limit="1" :on-success="handleSuccess" list-type="picture-card">
                        <!-- 内置 + 按钮 -->
                        <i class="el-icon-plus"></i>
                        <!-- 已上传图片预览 -->
                        <!-- <img :src="dialogImageUrl" alt="封面" style="width: 100%; height: 100%;"> -->
                    </el-upload>
                </el-form-item>

                <!-- 富文本编辑器 -->
                <el-form-item label="文章内容">
                    <Editor v-model="form.content" :height="400" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm(0)">保存</el-button>
                <el-button type="primary" @click="submitForm(1)">发布</el-button>
                <el-button type="primary" @click="handlePreview">预览</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>


        <div class="app-container">
            <!-- 文章预览组件 -->
            <ArticlePreview :article="previewArticle" :visible.sync="previewVisible"></ArticlePreview>
        </div>
    </div>
</template>
<script>
import { selectList, selectArticleById, insertArticle, updateArticle, deleteArticleById, selectColumnName, updateStatus, checkArticleCanRecall } from '@/api/publish/article/article.js'
import Editor from "@/components/Editor";
import ArticlePreview from "./ArticlePreview.vue";
export default {
    name: 'Article',
    components: {
        Editor,
        ArticlePreview
    },
    dicts: ['sys_normal_disable', 'wa_publish_article'],
    data() {
        return {
            //变量
            loading: true,
            total: 0,
            postList: [],//文章表格数据
            open: false,
            title: "",
            //查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                title: undefined,
                columnId: undefined,
                status: undefined,
                columnName: undefined
            },
            // 弹框表单参数
            form: {
                articleId: undefined,
                columnId: undefined,
                title: undefined,
                subTitle: undefined,
                content: "",
                image: null,
                status: '0',
                articleName: undefined
            },
            dialogImageUrl: "",
            dialogVisible: false,
            columnList: [],//存储栏目列表
            statusEnum: {
                DRAFT: "0",//草稿
                PUBLISHED: "1",//已发布
            },
            fileList: [], // el-upload 绑定的文件列表
            previewVisible: false,//预览弹窗显示
            previewArticle: {//存储预览的文章数据
                title: '',
                content: '',
                image: ''
            },

            // 表单校验
            rules: {
                columnId: [
                    { required: true, message: "栏目ID不能为空", trigger: "blur" }
                ],
                articleName: [
                    { required: true, message: "文章名称不能为空", trigger: "blur" }
                ],
                title: [
                    { required: true, message: "文章标题不能为空", trigger: "blur" }
                ],
                subTitle: [
                    { required: true, message: "文章副标题不能为空", trigger: "blur" }
                ]
            },

        };
    },
    //生命周期创建函数
    created() {
        this.getList();
        this.getColumnList();//加载栏目列表
    },
    methods: {
        //查询列表
        getList() {
            this.loading = true,
                selectList(this.queryParams).then(response => {
                    console.log("行数据", response);
                    this.postList = response.rows;//将响应数据给表格
                    this.total = response.total;
                    this.loading = false;

                }).catch(error => {
                    console.log("请求失败", error);
                });
        },

        //新增按钮操作
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = '添加文章'
        },
        //表单重置
        reset() {
            // 重置查询参数（清空所有条件）
            this.queryParams = {
                pageNum: 1,       // 重置页码为第1页
                pageSize: 10,     // 保持每页条数不变
                title: undefined, // 清空标题筛选
                columnId: undefined, // 清空栏目筛选
                status: undefined, // 清空状态筛选
                columnName: undefined
            };

            // 重置表单数据
            if (this.open) {
                this.form = {
                    articleId: undefined,
                    articleName: undefined,
                    columnId: undefined,
                    title: undefined,
                    status: '0',
                    content: ''
                };
                this.fileList = [];
                this.form.image = null;
                this.resetForm("form"); // 重置表单校验状态
            }

            // 显示所有数据
            this.getList();
        },
        //取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        //查询按钮
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        //获得栏目名称
        getColumnList() {
            selectColumnName().then(response => {
                console.log("栏目返回数据", response);
                this.columnList = response.data || [];
                this.columnList.forEach(column => {
                    console.log("栏目ID是否存在：", column.columnId); // 确认每个栏目都有columnId
                });
            }).catch(error => {
                console.log("获取栏目失败", error);

            })
        },
        //关闭对话框
        handleDialogClose() {
            this.reset();
            this.open = false;
        },
        //查询
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.postId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        beforeUpload(file) {
            const isValidType = ["image/jpeg", "image/png", "image/gif"].includes(
                file.type
            );
            const isValidSize = file.size / 1024 / 1024 < 5; // 限制5MB
            if (!isValidType) {
                this.$message.error("只能上传 JPG/PNG/GIF 格式的图片");
                return false;
            }
            if (!isValidSize) {
                this.$message.error("图片大小不能超过5MB")
                return false;
            }

            return true;
        },

        handleSuccess(response, file, fileList) {
            if (response.code === 200) {
                this.$message.success("上传成功");
                const baseUrl = "http://192.168.100.102:80/";
                this.form.image = baseUrl + response.data;
                console.log(this.form.image);
            } else {
                this.$message.error("上传失败" + response.msg);
            }
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        //移除图片
        handleRemove() {
            this.fileList = [];
            this.form.image = null;
        },
        // 提交（区分草稿/发布）
        submitForm(statusType) {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    // 设置文章状态（草稿或发布）
                    this.form.status = statusType === 1 ? '1' : '0';
                    // 根据 articleId 判断是新增还是修改
                    const apiFunc = this.form.articleId ? updateArticle : insertArticle;

                    // 调用接口
                    apiFunc(this.form).then(response => {
                        if (response.code === 200) {
                            this.$message.success(statusType === 1 ? '发布成功' : '保存成功');
                            this.open = false; // 关闭弹窗
                            this.getList(); // 刷新列表
                        } else {
                            this.$message.error('操作失败：' + response.msg );
                        }
                    }).catch(error => {
                        this.$message.error('请求失败：' + error.message);
                    });
                } else {
                    // 表单校验提示
                    this.$message.warning('请检查必填项');
                }
            });
        },
        // 预览文章页面
        handlePreview(row) {
            console.log("文章数据:", row);
            if (!row || !row.articleId) {
                this.$message.error('无效的文章ID');
                return;
            }
            this.loading = true;
            // 获取文章数据
            selectArticleById(row.articleId).then((response) => {
                this.previewArticle = response.data;//文章对象
                this.previewVisible = true;
                this.loading = false;//成功后重置加载状态
            }).catch(error => {

                this.$message.error("获取文章数据失败：" + error.message);
                //加载状态
                this.loading = false;
            })
        },
        //发布按钮操作
        handlePublish(row) {
            console.log("点击发布触发行", row);
            if (!row || !row.articleId) {
                this.$message.error("无法发布：文章数据无效");
                return;
            }
            const columnId = row.columnId;
            if (!columnId) {
                this.$message.error("发布失败：文章未关联栏目，请先编辑文章选择栏目");
                return;
            }
            const publishStatus = this.statusEnum.PUBLISHED; // 1（已发布）

            this.$confirm(`确定要发布文章《${row.title}》吗？`, "发布确认", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                // 直接传递 JSON 对象
                const params = {
                    articleId: row.articleId,
                    status: publishStatus,
                    columnId: row.columnId
                };

                // 调用发布接口
                updateStatus(params).then(response => {
                    console.log("发布接口返回", response);
                    this.$message.success("发布成功");
                    this.getList(); // 刷新列表

                }).catch(error => {
                    this.$message.error("发布失败：" + error.message);
                });
            })
        },

        /** 编辑按钮操作 */
        handleUpdate(row) {
            this.reset();
            selectArticleById(row.articleId).then((response) => {
                this.form = { ...response.data };//回显数据
                // 处理栏目ID
                if (this.form.columnId === "null" || this.form.columnId === "") {
                    this.form.columnId = undefined; // 为空时设为 undefined
                } else {
                    this.form.columnId = Number(this.form.columnId); // 确保是数字类型
                }
                // 处理图片路径（后端返回的是相对路径，拼接完整URL）
                if (this.form.image) {
                    const baseUrl = "http://192.168.100.102:80/";
                    this.form.image = this.form.image.startsWith("http")
                        ? this.form.image
                        : baseUrl + this.form.image;

                    // 预加载图片到 fileList
                    this.fileList = [{
                        url: this.form.image,
                        name: "preview.jpg",
                        status: "success"
                    }];
                }
                this.open = true;
                this.title = "修改文章";
            });
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            const articleId = row.articleId || this.ids;
            this.$modal.confirm('是否确认删除文章编号为"' + articleId + '"的数据项？').then(function () {
                return deleteArticleById(articleId);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        //撤回按钮
        handleRecall(row) {
            const currentRow = row || this.form;
            if (!currentRow.articleId) {
                this.$message.error("文章ID无效");
                return;
            }
            const articleId = Number(currentRow.articleId);
            if (isNaN(articleId)) {
                this.$message.error("文章ID格式错误");
                return;
            }

            //  先检查是否允许撤回（后端返回 true=可撤回，false=不可撤回）
            checkArticleCanRecall(articleId).then(canRecall => {
                if (!canRecall) {
                    this.$message.error("推荐中的文章不能撤回，请先取消推荐");
                    return;
                }

                // 允许撤回时，显示确认弹窗
                this.$confirm(`确定要撤回文章《${currentRow.title}》吗？撤回后将变为草稿状态。`, "撤回确认", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    //  执行撤回操作
                    const params = {
                        articleId: currentRow.articleId,
                        status: '0', // 撤回后变为草稿状态
                        columnId: currentRow.columnId
                    };

                    updateStatus(params).then(response => {
                        this.$message.success("撤回成功");
                        this.getList(); // 刷新列表
                    }).catch(error => {
                        this.$message.error("撤回失败：" + error.message);
                    });
                }).catch(() => {
                    this.$message.info("已取消撤回");
                });
            }).catch(error => {
                this.$message.error("检查推荐状态失败：" + (error.message || "网络异常"));
            });
        }
    }

}

</script>